<template>
  <div class="container">
    <div class="form">
      <div class="title">夕旅后台管理系统</div>
      <n-form ref="formRef" :model="formValue" size="medium" :rules="rules">
        <n-form-item path="username" :show-label="false">
          <n-input
            round
            v-model:value="formValue.username"
            placeholder="请输入账号"
          >
            <template #prefix>
              <n-icon :component="User" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item path="password" :show-label="false">
          <n-input
            round
            v-model:value="formValue.password"
            placeholder="请输入密码"
            type="password"
            show-password-on="mousedown"
            ><template #prefix>
              <n-icon :component="Lock" />
            </template>
          </n-input>
        </n-form-item>
        <n-form-item :show-label="false">
          <n-button round type="info" @click="handleValidateClick">
            登录
          </n-button>
        </n-form-item>
      </n-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInst } from 'naive-ui'
import { User, Lock } from '@vicons/fa'
import { login } from '@/api'
import { Md5 } from 'ts-md5'

const formRef = ref<FormInst | null>(null)

const formValue = ref({
  username: 'lixuan',
  password: 'flypig1223353861'
})

const rules = {
  username: { required: true, message: '请输入账号', trigger: 'blur' },
  password: { required: true, message: '请输入密码', trigger: 'blur' }
}

const router = useRouter()
const message = useMessage()
window.$message = useMessage()
const handleValidateClick = async (e: MouseEvent) => {
  e.preventDefault()
  const valid = await formRef.value?.validate(errors => !errors)
  if (!valid) return

  const res = await login({
    username: formValue.value.username,
    password: Md5.hashStr(formValue.value.password)
  })
  res && localStorage.setItem('token', res)
  message.success('登录成功')
  router.push('/home')
}
</script>

<style scoped lang="scss">
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: #d2d7ef;

  .form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 350px;
    padding: 30px;
    border-radius: 15px;
    background-color: #fff;

    .title {
      font-size: 24px;
      text-align: center;
      margin-bottom: 20px;
    }

    .n-button {
      width: 100%;
    }
  }
}
</style>
